<template>
  <div :style="{ border: '1px solid #ccc', height: props.height }">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :default-config="toolbarConfig"
    />
    <Editor
      v-model="valueHtml"
      style="overflow-y: hidden"
      :default-config="editorConfig"
      @onChange="onChange"
      @onCreated="handleCreated"
    />
  </div>
</template>
<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, getCurrentInstance, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IDomEditor } from '@wangeditor/editor'
const instance = getCurrentInstance()
const context = instance?.appContext.config.globalProperties
const BASIC_URL = import.meta.env.VITE_API_PATH
defineEmits(['change', 'update:modelValue'])
const props = defineProps({
  modelValue: String,
  height: { type: String, required: false, default: '400px' }
})
const editorRef = shallowRef()
const valueHtml = ref(props.modelValue)
// 模拟 ajax 异步获取内容
onMounted(() => {})
const toolbarConfig = {}
import request from '@/utils/request'
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      async customUpload(file: File, insertFn: InsertFnType) {
        const formData = new FormData()
        formData.append('file', file)
        request({
          url: BASIC_URL + '/file/upload',
          method: 'POST',
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          data: formData
        }).then((res) => {
          const path = BASIC_URL + '/file/downLoad/' + res.data
          insertFn(path, null, null)
        })
      }
    },
    uploadVideo: {
      async customUpload(file: File, insertFn: InsertFnType) {
        const formData = new FormData()
        formData.append('file', file)
        request({
          url: BASIC_URL + '/file/upload',
          method: 'POST',
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          data: formData
        }).then((res) => {
          const path = BASIC_URL + '/file/downLoad/' + res.data
          insertFn(path, null, null)
        })
      }
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor
}
const onChange = (editor: IDomEditor) => {
  instance.emit('update:modelValue', valueHtml.value)
  instance.emit('change', valueHtml.value)
}
watch(
  () => props.modelValue,
  (newVal, oldVal) => {
    if (newVal !== valueHtml.value) {
      valueHtml.value = newVal
    }
  }
)
</script>
